import { PrismaClient } from '@prisma/client';
import {
  registerDecorator,
  ValidationArguments,
  ValidationOptions,
} from 'class-validator';

const prisma = new PrismaClient();
/**
 * @description 判断是否存在于数据库，不存在则返回false
 * @param table 用户表
 * @param validationOptions 配置
 * @returns
 */
export function IsNotExistsRule(
  table: string,
  validationOptions?: ValidationOptions,
) {
  return function (object: Record<string, any>, propertyName: string) {
    registerDecorator({
      name: 'IsNotExistsRule',
      target: object.constructor,
      propertyName: propertyName,
      constraints: [table],
      options: validationOptions,
      validator: {
        async validate(value: string, args: ValidationArguments) {
          if (value) {
            //如果没有则返回null
            const res = await prisma[table].findFirst({
              where: {
                [args.property]: value,
              },
            });
            return Boolean(res);
          } else {
            return true;
          }
        },
      },
    });
  };
}
